package org.dbwebx.flex.module.bundle.presenter
{
	import flash.events.Event;
	import mx.collections.ArrayCollection;
	import org.dbwebx.domain.Bundle;
	import org.dbwebx.domain.SourceNode;
	import org.dbwebx.domain.User;
	import org.dbwebx.flex.delegate.impl.BundleService;
	import org.dbwebx.flex.delegate.impl.SourceNodeService;
	import org.dbwebx.flex.delegate.impl.UserService;
	import org.dbwebx.flex.presenter.AbstractPresenter;
	import org.fxcontainer.utils.Resource;

	/**
	 * The BundleManageForm presenter.
	 * @author Izzet_Mustafayev
	 */
	[Bindable]
	public class BundleManageFormPresenter extends AbstractPresenter implements IBundleManageFormPresenter
	{

		public function BundleManageFormPresenter()
		{
			super();
		}

		[Autowire(bean="BundleService")]
		public var bundleService:BundleService;

		[Autowire(bean="SourceNodeService")]
		public var sourceNodeService:SourceNodeService;

		[Autowire(bean="UserService")]
		public var userService:UserService;

		private var _sourceNodeList:ArrayCollection=new ArrayCollection();

		private var bundle:Bundle;

		private var sourceNode:SourceNode;

		private var user:User;

		[Mediate(event="bundleFormModelLoad")]
		/**
		 * Loads BundleManageForm data.
		 */
		public function loadModel():void
		{
			// TODO: check whether need to load all again
			if (null != sourceNodeService)
			{
				sourceNodeService.list(["bundleSourceNodeListLoaded"]);
			}
			if (null != userService)
			{
				userService.load(1, ["userLoaded"]);
			}
		}

		/**
		 * Get SourceNode ArrayCollection.
		 * @return the SourceNode ArrayCollection
		 */
		public function get sourceNodeList():ArrayCollection
		{
			return _sourceNodeList;
		}

		public function set sourceNodeList(v:ArrayCollection):void
		{
			_sourceNodeList=v;
		}
		
		/**
		 * Perform Bundle persisting.
		 * @param bundle the Bundle to persist.
		 */
		public function persistBundle(bundle:Bundle):void
		{
			bundleService.persist(bundle);
		}

		[Mediate(event="bundleSourceNodeListLoaded",properties="sourceNodes")]
		/**
		 * Handle retrueved SourceNode list.
		 * @param list the retrieved SourceNode list
		 */
		public function sourceNodeListReceiver(list:ArrayCollection):void
		{
			if (null != list)
			{
				var arr:Array=list.toArray();
				arr.unshift({name: Resource.getString('sourcenode.select.node')});
				sourceNodeList=new ArrayCollection(arr);
			}
		}

		/**
		 * Recieves <code>SourceNode</code> when it will be loaded.
		 */
		[Mediate(event="SourceNode:Loaded",properties="sourceNode")]
		public function sourceNodeReciever(_sourceNode:SourceNode):void
		{
			this.sourceNode=_sourceNode;
		}

		[Mediate(event="userLoaded",properties="user")]
		public function userReceiver(value:User):void
		{
			if (null != value)
			{
				user=value;
			}
		}
	}
}